"use strict"
angular.module("mymealplanrApp").controller "MainCtrl", ($scope, $http, Recipe,Event, Auth) ->
  $scope.eventSources = []

  $scope.dateOptions =
    'year-format': "'yy'"
    'starting-day': 1
  
  if Auth.isLoggedIn()
    recipes = Recipe.get({name: $scope.currentUser.name})
    events = Event.get({name: $scope.currentUser.name})
  else
    recipes = Recipe.get({name: 'Test User'})
    events = Event.get({name: 'Test User'})
    
  recipes.$promise.then ->
    $scope.recipes = recipes.recipes
    if not Auth.isLoggedIn()
      $scope.events = populateEventsForRecipes($scope.recipes)
      handleWeekends event for event in $scope.events
      $scope.eventSources.push $scope.events

    return

  events.$promise.then ->
    if Auth.isLoggedIn()
      events.events.forEach (event) ->
        event.backgroundColor= '#2C343B'
        event.borderColor= '#7c7c7c'
        handleWeekends(event)
        return
      $scope.events = events.events
      $scope.eventSources.push $scope.events


  $scope.uiConfig =
    calendar:
      editable: true
      droppable: true
      eventRender: (event,element,view) ->
        recipeForEvent = getRecipeForEventTitle(event.title)
        content = "<a href='"+recipeForEvent.source+"' target='_blank'><img width='200px' height='200px' src='"+recipeForEvent.image+"'/></a>" if recipeForEvent?
        element.popover({
          title: event.title
          placement: "bottom"
          html: true
          content: content
          container: 'body'
          })
      eventDrop: (event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) ->
        oldDate = new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate() - dayDelta)
        if Auth.isLoggedIn()
          Event.update({
            oldDate: oldDate
            newDate: event.start
            name: $scope.currentUser.name
            })
        $scope.$apply ->
          $scope.alertMessage = "Create an accout or login to save changes!" if not Auth.isLoggedIn()
          return
        return
      drop: (date, allDay) ->
        source = $(this).children().attr('href')
        title = $(this).children().text()
        recipeForEvent = getRecipeForEventTitle(title)
        event = createEvent($.trim(title), date, source)

        $scope.$apply ->
          addEventToEvents(event)
          $scope.alertMessage = "Create an accout or login to save changes!" if not Auth.isLoggedIn()
          return

        return

  getRecipeForEventTitle = (title) ->
    return unless $scope.recipes
    (recipe for recipe in $scope.recipes when recipe.title is title)[0] || null
    
  createEvent = (title,date,link) ->

    return {
      title: title
      start: new Date(date)
      link: link
      backgroundColor: '#2C343B'
      borderColor: '#7c7c7c'
    } if date

  removeEvent = (event) ->
    $scope.$apply ->
      $scope.events.splice($scope.events.indexOf(event),1)

  createEvents = (recipe) ->
    recipe.scheduled.forEach (date) ->
      event = createEvent(recipe.title, date, recipe.source)
      $scope.events.push(event)

    return

  $scope.createRecipe = (title,url,image,date) ->
    date = new Date(date) if date
    event = createEvent(title,date,url)


    addEventToEvents(event)

    angular.element('#myModal').modal('hide')

    recipe =
      title: title
      image: image
      source: url
    
    recipe.scheduled = [date] if date

    if Auth.isLoggedIn()
      recipe.name = $scope.currentUser.name
      Recipe.save(recipe)
      if event
        event.name = $scope.currentUser.name
        Event.save(event)

    $scope.recipes.push(recipe) if $scope.recipes
    
    return
  
  addEventToEvents = (event) ->
    return unless event
    if($scope.events is undefined)
      $scope.events = []
    found = -1
    i = 0
    while i < $scope.events.length
      eventDate = $scope.events[i].start
      if eventDate.getMonth() is event.start.getMonth() &&
         eventDate.getDate() is event.start.getDate() &&
         eventDate.getFullYear() is event.start.getFullYear()
         
        found = i
        break
      i++

    if found isnt -1
      $scope.events[found] = event
    else
      $scope.events.push(event)

    event

  isWeekend = (date) ->
    dayOfWeek = date.getDay()
    dayOfWeek is 6 or dayOfWeek is 0

  handleWeekends = (event) ->
    return unless event
    if(not event.start.getMonth)
      event.start = new Date(event.start)
    dayOfWeek = event.start.getDay()
    if dayOfWeek is 6 or dayOfWeek is 0
      event.backgroundColor = '#C44741'
    if dayOfWeek is 0
      event.title = 'Free Day'
    return

  populateEventsForRecipes = (recipes) ->
    events = []
    date = new Date()
    lastDayOfMonth = new Date(date.getFullYear(), date.getMonth()+1, 0).getDate()

    i = 1
    while i < lastDayOfMonth+1
      rand = Math.floor(Math.random() * recipes.length)

      randomRecipe = recipes[rand]
      event = createEvent(randomRecipe.title,new Date(date.getFullYear(), date.getMonth(), i),randomRecipe.source)
      events.push event
        
      ++i

    shuffle events

  shuffle = (array) ->
    m = array.length
    t = undefined
    i = undefined
  
    # While there remain elements to shuffle…
    while m
    
      # Pick a remaining element…
      i = Math.floor(Math.random() * m--)
    
      # And swap it with the current element.
      t = array[m]
      array[m] = array[i]
      array[i] = t

    array

  $scope.open = ($event) ->
    $event.preventDefault()
    $event.stopPropagation()

    $scope.opened = true

  $scope.regenerateMealPlan = ->
    date = new Date()
    lastDayOfMonth = new Date(date.getFullYear(), date.getMonth()+1, 0).getDate()
    parameters =
      start: "#{date.getFullYear()}-#{date.getMonth()+1}-1"
      end: "#{date.getFullYear()}-#{date.getMonth()+1}-#{lastDayOfMonth}"

    eventsForDateRange = Event.get(parameters)
    eventsForDateRange.$promise.then ->
      if(eventsForDateRange.events)
        shuffle eventsForDateRange.events
        i = 0
        while i < eventsForDateRange.events.length
          eventsForDateRange.events[i].start = new Date(date.getFullYear(), date.getMonth(), i+1)
          ++i

        $scope.events = eventsForDateRange.events
      else
        alert('didnt work')
  
  return
